package com.qf.pay.service.impl;

import cn.hutool.jwt.JWTUtil;
import com.qf.api.point.dto.PointRetryDTO;
import com.qf.api.point.feign.PointFeignService;
import com.qf.common.core.config.ThreadPoolConfig;
import com.qf.common.core.entity.DropOrder;
import com.qf.common.core.entity.Recharge;
import com.qf.common.core.exception.CustomerException;
import com.qf.common.core.utils.R;
import com.qf.common.core.utils.UserUtils;
import com.qf.common.pay.param.PayFinishParam;
import com.qf.common.pay.param.PayParam;
import com.qf.common.pay.service.PayService;
import com.qf.common.redis.utils.RedisUtil;
import com.qf.drop.service.DropOrderService;
import com.qf.pay.param.OrderPayParam;
import com.qf.pay.param.PayStatusParam;
import com.qf.pay.service.OrderPayService;
import com.qf.recharge.service.RechargeService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;

/**
 * @author zdl
 * @date 2025/4/1
 */
@Service
public class OrderPayServiceImpl implements OrderPayService {
    @Resource(name = "aliPayServiceImpl")
    private PayService aliPayService;
    @Resource(name = "wxPayServiceImpl")
    private PayService wxPayService;
    @Resource
    private RechargeService rechargeService;

    @Resource
    private ThreadPoolConfig threadPoolConfig;

    @Resource
    private DropOrderService dropOrderService;

    @Resource
    private RedisUtil redisUtil;

    @Resource
    private PointFeignService pointFeignService;

    @Override
    public String pay(OrderPayParam orderPayParam) {
        Recharge recharge = rechargeService.rechargeByOrderNo(orderPayParam.getOrderNo());
        if (!recharge.getStatus().equals(1)) {
            throw new CustomerException("3003", "订单不是待支付状态，无法支付");
        }
        if (orderPayParam.getAmount().compareTo(recharge.getPrice()) != 0) {
            throw new CustomerException("3004", "支付金额与订单金额不一致");
        }
        PayParam payParam = new PayParam();
        //生成业务订单号
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        //payParam.setOutTradeNo(sdf.format(new Date()));
        payParam.setOutTradeNo(orderPayParam.getOrderNo());
        payParam.setSubject("充值");
        payParam.setTotalAmount(new BigDecimal("0.01"));
        String url = null;
        if (recharge.getPlatformType().equals(2)) {
            // 调用支付宝支付接口
            url = aliPayService.createPayOrder(payParam);
        } else if (recharge.getPlatformType().equals(1)) {
            // 调用 微信支付
            url = wxPayService.createPayOrder(payParam);
        }
        // 生成调单数据
        DropOrder dropOrder = new DropOrder();
        dropOrder.setOrderNo(orderPayParam.getOrderNo());
        dropOrderService.addDropOrder(dropOrder);
        return url;
    }

    @Override
    public void notify(HttpServletRequest request, HttpServletResponse response, Integer platformType) {
        if (platformType.equals(2)) {
            PayFinishParam param = aliPayService.notify(request, response);
            Recharge recharge = rechargeService.rechargeByOrderNo(param.getOrderNo());
            if (param != null) {
                // 修改订单数据
                threadPoolConfig.taskExecutor().execute(() -> {
                    rechargeService.updateRecharge(param);
                    //  调用远程送积分的接口
                    R<?> r = pointFeignService.remoteAddPoint3(4,recharge.getUid());
                    if (r.getCode().equals(500)){

                        // 进行积分补偿，将数据添加到积分补偿表中
                        PointRetryDTO dto = new PointRetryDTO();
                        dto.setUid(recharge.getUid());
                        dto.setPointType(4);
                        pointFeignService.addPointRetry(dto);
                    }

                });
            }
        }
        if (platformType.equals(1)) {
            // wxPayService.notify(request, response);
        }

    }

    @Override
    public void notify2(HttpServletRequest request, HttpServletResponse response, Consumer<String> consumer) {
        // 参数是 包含订单编号等数据的对象
        // consumer.accept(request.getParameter("out_trade_no"));
    }


    /**
     * 掉单处理
     *
     * @param orderNo
     * @return
     */
    @Override
    public PayStatusParam checkPayStatus(String orderNo, Integer num) {
        String tradeNo = null;
        int status = 0;

        // 如果达到最大次数，则关闭订单，调单表中删除数据
        if (num == 12) {
            aliPayService.closePay(orderNo);
            status = 3;
        } else {
            try {
                // 没有达到最大次数，则判断交易订单的状态，如果已经支付，从调单表中删除数据
                tradeNo = aliPayService.payStatus(orderNo);
                status = 1;
            } catch (Exception e) {
                // 还是未支付状态，进行下次轮询，同时需要更新调单表中轮询次数字段
                status = 2;
            }
        }
        PayStatusParam param = new PayStatusParam();
        param.setStatus(status);
        param.setTradeNo(tradeNo);
        return param;

    }

    @Override
    public String refund(String orderNo) {

        aliPayService.refund(orderNo);
        return "退款成功";
    }

    @Override
    public void returnNotify(HttpServletRequest request, HttpServletResponse response) {
        aliPayService.returnNotify(request, response);
    }

    @Override
    public String getToken() {
        String token = UUID.randomUUID().toString().replace("-", "");
        Integer uid = UserUtils.getUser();
        // 将token存入redis
        String key = String.format("repeat:%s:%s", token, uid);
        redisUtil.setCacheObject(key, 1, 60 * 5, TimeUnit.SECONDS);
        return token;
    }
}
